package server;

import java.util.concurrent.LinkedBlockingQueue;

import model.Message;
import server.exception.ClientDoesNotExistException;

public class DispatcherThread extends Thread
{

	private LinkedBlockingQueue<Message> messageQueue;
	
	public DispatcherThread()
	{
		this.messageQueue = new LinkedBlockingQueue<Message>();
	}
	
	@Override
	public void run()
	{
		while (true)
		{
			try
			{
				Message message = this.messageQueue.take();
				System.out.println(message);
				
				switch (message.getType())
				{
					case TEXT_MESSAGE_TO_CLIENT:
					case LIST_ONLINE_CLIENTS:
					case LOGIN_ACCEPTED:
					case LOGOUT_ACK:
						messageToClientTreatment(message);
						break;
					case LOGIN_REFUSED:
						messageToNegotiationClientTreatment(message);
						break;
					case VERIFY_LOGIN:
					case TEXT_MESSAGE_TO_SERVER:
					case LOGOUT_REQUEST:
						messageToServerTreatment(message);
						break;
					default:
						break;
				}
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}

	private void messageToServerTreatment(Message message)
	{
		ServerMain.addMessage(message);
	}

	private void messageToClientTreatment(Message message)
	{
		String to = message.getTo();
		if (to == null)
		{
			return;
		}
		
		try
		{
			ServerMain.getClient(to).sendMessage(message);
		}
		catch (ClientDoesNotExistException e)
		{
			e.printStackTrace();
		}
	}
	
	private void messageToNegotiationClientTreatment(Message message)
	{
		String to = message.getTo();
		try
		{
			ServerMain.getNegotiationClient(to).sendMessage(message);
		}
		catch (ClientDoesNotExistException e)
		{
			e.printStackTrace();
		}
	}
	
	public void addMessage(final Message message)
	{
		try
		{
			this.messageQueue.put(message);
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
	}
}
